export async function onRequestPost(context) {
const { prompt } = await context.request.json();
const query = prompt.toLowerCase();
// Gets the site URL automatically
const host = new URL(context.request.url).origin;
const pdfUrl = host + "/SNGPL_Manual.pdf";
// --- FORM LOOKUP TABLE ---
const forms = [
{ name: "Work Permit", keywords: ["permit", "hpr002", "hpr-002", "ijazat"], page: 243 },
{ name: "Incident Report", keywords: ["incident", "accident", "reporting", "hadsa", "gpr008"], page: 100 },
{ name: "Vehicle Fitness", keywords: ["vehicle", "fitness", "gari", "hpr007"], page: 330 },
{ name: "PPE Proforma", keywords: ["ppe", "helmet", "shoes", "hpr005"], page: 314 },
{ name: "Color Codes", keywords: ["color", "colour", "paint", "pipe", "hpr015"], page: 413 }
];
let found = forms.find(f => f.keywords.some(k => query.includes(k)));
let actionLink = found ? `
🔗 Link: Open ${found.name} (Manual Page ${found.page})` : "";
// --- AI LOGIC ---
const systemPrompt = `You are the SNGPL HSE AI.
Answer only using the SNGPL Manual 2021.
Reply in under 3 sentences.
If user uses Urdu/Roman Urdu, reply in Urdu.
NEVER say "I don't have the link". The system will add it automatically.`;
try {
const aiResponse = await context.env.AI.run('@cf/meta/llama-3-8b-instruct', {
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: prompt }
],
max_tokens: 150
});
return new Response(JSON.stringify({
response: aiResponse.response + actionLink
}));
} catch (e) {
return new Response(JSON.stringify({ response: "System busy. Try again." }));
}
}